package org.anupta.game.server.inter;

import org.anupta.game.main.Main;
import org.anupta.game.server.inter.client.InterClient;
import org.anupta.game.utils.others.Config;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class InterHandler extends IoHandlerAdapter {
	@Override
    public void sessionCreated(IoSession session) throws Exception {
		Main.out.println(new StringBuilder("GameServer connected : ").append(Config.INTER_IP).append(":").append(Config.INTER_PORT).toString());
        session.setAttribute("client", new InterClient(session));
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message == null) {
            return;
        }
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof InterClient) {
            InterClient client = (InterClient) objC;
            if(message instanceof IoBuffer){
            	IoBuffer buffer = IoBuffer.allocate(2048);
            	buffer.put((IoBuffer)message);
            	buffer.flip();
            	client.parse(buffer);
            }
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof InterClient) {
            InterClient client = (InterClient) objC;
            client.quit();
        }
        session.removeAttribute("client");
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof InterClient) {
            InterClient client = (InterClient) objC;
            client.quit();
        }
    }
}
